#!/bin/sh

arch="mipsel" #armv6l
arch-static="mipsel"  #arm
static="/usr/bin/qemu-${arch-static}-static"
native="native-compiler-$arch"
rootfs="root-filesystem-$arch"
url="http://www.landley.net/code/aboriginal/downloads/binaries/root-filesystem/"

if [ ! -f "$static" ]
then
  sudo apt-get install qemu-user-static
fi

mkdir "$arch"
cd "$arch"

echo "Getting ${url}${native}.tar.gz"
wget -c "${url}${native}.tar.gz"
echo "Getting ${url}${rootfs}.tar.gz"
wget -c "${url}${rootfs}.tar.gz"

tar xvzf ${native}.tar.gz
tar xvzf ${rootfs}.tar.gz

cd "$rootfs"
sudo cp -r ../${native}/* ./
#rm ../${native}* -fr
#rm ../${rootfs}.tar.gz

cp "$static" bin
cd usr/bin
find . -maxdepth 1 -type l -exec rm -f {} \;
rm busybox
wget "http://www.busybox.net/downloads/binaries/latest/busybox-$arch" -O busybox
chmod +x busybox
busybox  --help | \
sed -e '1,/^Currently defined functions:/d' \
    -e 's/[ \t]//g' -e 's/,$//' -e 's/,/\n/g' | \
while read app ; do
  if [ "$app" != "" ]; then
    printf "linking %-12s ...\n" "$app"
    ln -sf "./busybox" "$app"
    ls -ld "$app"
  fi
done
cd ../../

cat << EOF > hello.c
#include<stdio.h>

main()
{   
    printf("Hello World\n");

}
EOF

echo "Entering $arch chroot environment..."
echo "Run the following to test compiler:"
echo "gcc -static hello.c -o hello"
sudo chroot . sh